<?php

namespace app\api\controller;

use app\admin\model\teacher\Share;
use app\common\controller\Api;
use app\common\model\User;
use think\Db;

class Activity extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 查询首页活跃度
     */
    public function index()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
        //查询用户昵称
        $nickname = Db::table('fa_user')->where('id', $uid)->field('nickname,avatar,jointime')->find();
        //查询直推粉丝数量和活跃度
        $firstCount = Share::where('user_id', $uid)->field('id,first_children,active_zong,active_ge')->find();
        //查询我的上级
        $parent = Db::table('fa_user')->where('id', $uid)->field('pid')->find();
        $parentInfo = Db::table('fa_user')->where('id', $parent['pid'])->field('id,nickname,avatar')
            ->find();
        //查询粉丝列表
        $fansList = Db::table('fa_user')->where('pid', $uid)->field('id,nickname,avatar,jointime')->select()->toArray();
        $fansActive = [];
        foreach ($fansList as $key => $value) {
            $fansActive[] = Share::where('user_id', $value['id'])->field('user_id,active_zong,active_ge')->find();
            $fansList[$key]['jointime'] = date('Y-m-d H:i:s', $value['jointime']);
        }
//        $this->success('',$fansActive);
        foreach ($fansList as &$fan) {
            // 查找与当前粉丝ID匹配的活动记录
            $matchingActive = null;
            foreach ($fansActive as $kk => $active) {
                if (!is_null($active) && $active['user_id'] === $fan['id']) {
                    $matchingActive = $active;
                    break; // 找到匹配项后立即跳出循环
                }
            }
            // 如果找到匹配的活动记录，则将其 active_zong 值赋予粉丝数据
            if (!is_null($matchingActive)) {
                $fan['active_zong'] = $matchingActive['active_zong'];
                $fan['active_ge'] = $matchingActive['active_ge'];
            } else {
                // 或者设置一个默认值或空值
                $fan['active_zong'] = 0;
            }
        }
        if ($parentInfo) {
//            $parentInfo['jointime'] = $nickname['jointime'];
            $parentInfo['jointime'] = date('Y-m-d H:i:s', $nickname['jointime']);
        }
        unset($nickname['jointime']);
        $this->success('', ['user' => $nickname,
            'userActive' => $firstCount,
            'parentInfo' => $parentInfo,
            'list' => $fansList]);
    }

    /**
     * 查询大区活跃度
     */
    public function regionActive()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
        //查询总活跃度（用户的active_zong）
        $activeCount = Share::where('user_id', $uid)->field('active_zong,active_ge')->find();
        //查询直推粉丝id
        $spurLine = Db::table('fa_user')->where('pid', $uid)->field('id,nickname,avatar')->select()->toArray();
        //查询大区支线
        $activeMax = [];
        $maxActiveZong = 0;
        $maxObject = [];//如果没有大区支线，返回空
        $maxObject1 = [];
        $maxUserList = [];
        foreach ($spurLine as $key => $value) {
            $activeMax[] = Share::where('user_id', $value['id'])->field('user_id,active_zong,first_children')->find();
            foreach ($activeMax as $item) {
                if (is_null($item)) {
                    continue;
                }
                // 如果当前元素的 active_zong 大于已知的最大值
                if (isset($item->active_zong) && $item->active_zong > $maxActiveZong) {
                    $maxActiveZong = $item->active_zong;
                    $maxObject = $value;
                    $maxObject1['count'] = $item->first_children;
                    $maxObject1['active'] = $item->active_zong;
                }
            }
        }
        //查询大区用户
        if (!empty($maxObject)) {
            $maxUserList = Db::table('fa_user')->where('pid', $maxObject['id'])->field('id,nickname,avatar')->select()->toArray();
        }
        foreach ($maxUserList as $key => $value) {
            $maxUserListActive[] = Share::where('user_id', $value['id'])->field('user_id,active_zong,active_ge,first_children')->find();
            foreach ($maxUserListActive as $item) {
                $maxUserList[$key]['active_zong'] = $item['active_zong'];
                $maxUserList[$key]['active_ge'] = $item['active_ge'];
            }
        }
        $this->success('', [
            'activeCount' => $activeCount,//总活跃度
            'maxSpur' => $maxObject,//大区支线
            'Active' => $maxObject1,
            'userList' => $maxUserList//大区支线用户
        ]);
    }

    /**
     * 查询小区活跃度
     */
    public function communityActive()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
        //查询总活跃度（用户的active_zong）
        $activeCount = Share::where('user_id', $uid)->field('active_zong,active_qu,active_ge')->find();
        //查询直推粉丝id
        $spurLine = Db::table('fa_user')->where('pid', $uid)->field('id,nickname,avatar')->select()->toArray();
        //查询大区支线
        $activeMax = [];
        $maxObjectId = [];
        $maxActiveZong = 0;
        foreach ($spurLine as $key => $value) {
            $item = Share::where('user_id', $value['id'])->field('user_id,active_zong,first_children')->find();
            if (is_null($item)) {
                continue;
            }
            // 如果当前查询结果的 active_zong 大于已知的最大值
            if (isset($item->active_zong) && $item->active_zong > $maxActiveZong) {
                $maxActiveZong = $item->active_zong;
                $maxObjectId = $value['id'];
            }
        }
        // 删除具有最大 active_zong 的对象（基于其 id）
        if ($maxObjectId !== null) {
            foreach ($spurLine as $key => $value) {
                if ($value['id'] === $maxObjectId) {
                    unset($spurLine[$key]);
                    break;
                }
            }
        }
        // 将剩余的用户列表重新索引
        $indexedData = array_values($spurLine);
        $minSpurList = [];
        // $this->success('',$indexedData);
        foreach ($indexedData as $k => $value) {
            if (is_null($value)) {
                continue;
            }
            $userActivity = Share::where('user_id', $value['id'])->field('active_zong,active_ge,first_children')->find();
            // 将活跃数据合并到子用户详情中
            if (!empty($userActivity)) {
                $indexedData[$k]['active'] = $userActivity['active_zong'];
                $indexedData[$k]['active_ge'] = $userActivity['active_ge'];
            } else {
                // 或者设置一个默认值或空值
                $indexedData[$k]['active'] = 0;
                $indexedData[$k]['active_ge'] = 0;

            }
        }
        // 提取 active 字段作为排序依据
        $activeValues = array_column($indexedData, 'active');
        // 使用 array_multisort() 函数进行排序
        array_multisort($activeValues, SORT_DESC, $indexedData);
//        $this->success('',$indexedData);
        $this->success('', ['activeCount' => $activeCount,
            'Active' => ['active' => $activeCount['active_qu'],
                'count' => count($indexedData)],
            'userList' => $indexedData
        ]);
    }
}